package com.qwer.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class AesEncrypt {
    private static final String AES = "AES";
    private static final String PADDING = "AES/CBC/PKCS5Padding";// "算法/模式/补码方式"
    private static final String DEFAULT_ENCODING = "utf-8";
    private static final String IV = "1234567812345678";

    /**
     * 加密
     * 
     * @Title: encrypt
     * @Description: 加密
     * @param code
     * 明文
     * @param key
     * 密钥
     * @return 密文
     * @return String 返回类型
     * @throws
     */
    public static String encrypt(String code, String key) {
        try {
            return new Base64()
                .encodeToString(encrypt(code.getBytes(DEFAULT_ENCODING), key.getBytes(DEFAULT_ENCODING)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] encrypt(byte[] code, byte[] key) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(key, AES);
        Cipher cipher = Cipher.getInstance(PADDING);// "算法/模式/补码方式"
        // 使用CBC模式，需要一个向量iv，可增加加密算法的强度
        IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
        return cipher.doFinal(code);
    }

    /**
     * 解密
     * 
     * @Title: decrypt
     * @Description: 解密
     * @param data
     * 密文
     * @param key
     * 密钥
     * @return 明文
     * @return String 返回类型
     * @throws
     */
    public static String decrypt(String data, String key) {
        try {
            return new String(decrypt(data.getBytes(DEFAULT_ENCODING), key.getBytes(DEFAULT_ENCODING)),
                DEFAULT_ENCODING);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] decrypt(byte[] src, byte[] key) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(key, AES);
        Cipher cipher = Cipher.getInstance(PADDING);
        IvParameterSpec iv = new IvParameterSpec(IV.getBytes(DEFAULT_ENCODING));
        cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
        byte[] _src = new Base64().decode(src);
        return cipher.doFinal(_src);
    }

    public static void main(String[] args) {
        String key = "8Qg722AOdIbtDKef";

        String code = "{\"emplid\":\"admin\",\"emplpass\":\"123\"}";
        System.out.println("code=" + code);

        String encryptData = encrypt(code, key);
        System.out.println("encryptData=" + encryptData);

        String data = decrypt(encryptData, key);
        System.out.println("data=" + data);
    }
}
